//
//  QCSetupView.swift
//  爱汽车
//
//  Created by liujianlong on 2023/8/25.
//

import UIKit
enum QCSetupViewStyle : Equatable{
    case normal(_ selectImgShowTime:Int?=0)
    case check(_ selectImgShowTime:Int?=0)
    case custom(_ selectImgShowTime:Int?=0)
    static func ==(lhs: QCSetupViewStyle, rhs: QCSetupViewStyle) -> Bool {
        switch (lhs, rhs) {
        case (.normal, .normal),
            (.check, .check),
            (.custom, .custom):
            return true
        default:
            return false
        }
    }
}
class QCSetupView: UIView {
    var timer: Timer?
    var currentLongPressBtn = [UIButton]()
    ///左前气压值
    @IBOutlet var value1: UILabel!
    ///左后气压值
    @IBOutlet var value2: UILabel!
    ///右前气压值
    @IBOutlet var value3: UILabel!
    ///左后气压值
    @IBOutlet var value4: UILabel!
    ///左前 + 气压值  tag=201
    @IBOutlet var btn1: UIButton!
    ////左前 - 气压值  tag=202
    @IBOutlet var btn2: UIButton!
    ///左后 + 气压值  tag=203
    @IBOutlet var btn3: UIButton!
    ///左后 - 气压值   tag=204
    @IBOutlet var btn4: UIButton!
    ////右前 + 气压值 tag=205
    @IBOutlet var btn5: UIButton!
    ///右前 - 气压值   tag=206
    @IBOutlet var btn6: UIButton!
    ///右后 + 气压值  tag=207
    @IBOutlet var btn7: UIButton!
    ///右后- 气压值    tag=208
    @IBOutlet var btn8: UIButton!
    ///左右前，一起 + 气压值  tag=209
    @IBOutlet var btn9: UIButton!
    ///左右前，一起 - 气压值   tag=210
    @IBOutlet var btn10: UIButton!
    ///左右后，一起 + 气压值   tag=211
    @IBOutlet var btn11: UIButton!
    ///左右前，一起 - 气压值    tag=212
    @IBOutlet var btn12: UIButton!
    ///左边的滑动条，气缸气压
    lazy var slider1:QCSetupSlider = {
        let slider = QCSetupSlider.loadFromXIB()
        self.addSubview(slider)
        return slider as! QCSetupSlider
    }()
    ///右边的滑动条，气缸温度
    lazy var slider2:QCSetupSlider = {
        let slider = QCSetupSlider.loadFromXIB()
        self.addSubview(slider)
        return slider as! QCSetupSlider
    }()
    ///中间上边的滑动条，展示：左前的高度，右前的高度
    lazy var slider3:QCSetupSlider = {
        let slider = QCSetupSlider.loadFromXIB()
        self.addSubview(slider)
        return slider as! QCSetupSlider
    }()
    ///中间下边的滑动条，展示：左后的高度，右后的高度
    lazy var slider4:QCSetupSlider = {
        let slider = QCSetupSlider.loadFromXIB()
        self.addSubview(slider)
        return slider as! QCSetupSlider
    }()
    private var array = [UIButton]()
    ///自定义高度选择的档位
    var customDangwei = 0
    var style = QCSetupViewStyle.normal() {
        didSet{
            switch style{
            case let .normal(time):
                slider1.isHidden = false
                slider2.isHidden = false
                slider3.type.showSelectTime = time
                slider4.type.showSelectTime = time
            case let .check(time):
                slider1.isHidden = true
                slider2.isHidden = true
                slider3.type.showSelectTime = time
                slider4.type.showSelectTime = time
            case let .custom(time):
                slider1.isHidden = false
                slider2.isHidden = false
                slider3.type.showSelectTime = time
                slider4.type.showSelectTime = time
            }
        }
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        initUI()
    }
    func initUI(){
        array = [btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9,btn10,btn11,btn12]
        for btn in array{
            let long = UILongPressGestureRecognizer(target: self, action: #selector(actionForlongPress))
            btn.addGestureRecognizer(long)
        }
        slider3.lineWidth.constant = 1
        slider4.lineWidth.constant = 1
        slider1.showGradientColor = false///取消渐变色
        slider2.showGradientColor = false///取消渐变色
        slider3.showGradientColor = false///取消渐变色
        slider4.showGradientColor = false///取消渐变色
        slider1.type = QCSetupSliderMode(thumImg: "气压",limit:(min: 0,max: 150),current:(left:0,right:0),target: (left: 0, right: 0),showSelectTime:0)
        slider2.type = QCSetupSliderMode(thumImg: "气温",limit:(min: 0,max: 120),current:(left:0,right:0),target: (left: 0, right: 0),showSelectTime:0)
        slider3.type = QCSetupSliderMode(thumImg: "",limit:(min: 0,max: 100),current:(left:0,right:0),target: (left: 0, right: 0),showSelectTime:0)
        slider4.type = QCSetupSliderMode(thumImg: "",limit:(min: 0,max: 100),current:(left:0,right:0),target: (left: 0, right: 0),showSelectTime:0)
        attrText(0, lbl: value1)
        attrText(0, lbl: value2)
        attrText(0, lbl: value3)
        attrText(0, lbl: value4)
        slider1.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.width.equalTo(60)
            make.top.equalTo(value1.snp.centerY)
            make.bottom.equalTo(value2.snp.centerY)
        }
        
        slider2.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.width.equalTo(60)
            make.top.equalTo(value3.snp.centerY)
            make.bottom.equalTo(value4.snp.centerY)
        }
        
        slider3.snp.makeConstraints { make in
            make.centerX.equalTo(btn9)
            make.width.equalTo(60)
            make.top.equalTo(btn9.snp.bottom)
            make.bottom.equalTo(btn10.snp.top)
        }
        
        slider4.snp.makeConstraints { make in
            make.centerX.equalTo(btn11)
            make.width.equalTo(60)
            make.top.equalTo(btn11.snp.bottom)
            make.bottom.equalTo(btn12.snp.top)
        }
        slider1.isHidden = style == .check()
        slider2.isHidden = style == .check()
    }
    
    var bytes = [UInt8](){
        didSet{
            let ack = bytes[7]
            let data = [UInt8](bytes[AI_index..<bytes.count])
            switch ack{
            case UInt8(AIQC.infoStatus.ack):
                let scale1 = CGFloat(Int(data[7])) / CGFloat(slider1.type.limit.max)
                let scale2 = CGFloat(Int(data[21])) / CGFloat(slider2.type.limit.max)
                slider1.bg_shape.fillColor = getCgcolor(scale1)///根据气缸气压当前值，改变进度条整条颜色
                slider2.bg_shape.fillColor = getCgcolor(scale2)///根据气缸温度当前值，改变进度条整条颜色
                slider1.type.current = (left:Int(data[7]), right:Int(data[7]))///气缸气压当前值
                slider2.type.current = (left:Int(data[21]), right:Int(data[21]))///气缸温度当前值
                slider3.type.current = (left:Int(data[8]), right:Int(data[9]))///左右前高度工作量
                slider4.type.current = (left:Int(data[10]), right:Int(data[11]))///左右后高度工作量
                if style == .check() || style == .normal(){
                    slider3.type.target = (left:Int(data[12]), right:Int(data[13]))///左右前，当前档位目标高度工作量
                    slider4.type.target = (left:Int(data[14]), right:Int(data[15]))///左右后，当前档位目标高度工作量
                }
                attrText(Int(data[3]), lbl: value1)///左前气压值
                attrText(Int(data[5]), lbl: value2)///左后气压值
                attrText(Int(data[4]), lbl: value3)///右前气压值
                attrText(Int(data[6]), lbl: value4)///右后气压值
                
                ///档位
                let bit = Int(data[2])
                slider3.type.dangwei = bit & 0xF///Bit0~bit3: 0:手动位置, 1~5:档位1~5
                slider4.type.dangwei = bit & 0xF///Bit0~bit3: 0:手动位置, 1~5:档位1~5
                
            case UInt8(AIQC.userInfo.ack):
                slider1.type.limit = (min:0, max:Int(data[87]))
                ///0，如果是自定义高度设置
                guard case .custom(_) = style else { return}
                ///1，对应档位下，开始坐标
                let start = 6 + customDangwei * 8
                let l_f = decimal(start)///左前，当前档位目标高度工作量
                let r_f = decimal(start+2)///右前，当前档位目标高度工作量
                let l_b = decimal(start+4)///左后，当前档位目标高度工作量
                let r_b = decimal(start+6)///右后，当前档位目标高度工作量
                slider3.type.target = (left:l_f, right:r_f)///左右前，当前档位目标高度工作量
                slider4.type.target = (left:l_b, right:r_b)///左右后，当前档位目标高度工作量
                
                ///2，两个字节的预置高度值，转变成10进制
                func decimal(_ m:Int)->Int{
                    return String(format: "%02X%02X", data[m],data[m+1]).toDecimal()
                }
            default:
                break
            }
            
            for btn in array{
                btn.isSelected = currentLongPressBtn.contains(btn)
            }
        }
    }
    
    @IBAction func actionForBtn(_ sender: UIButton) {
        for btn in array{
            btn.isSelected = sender == btn
        }
        send(sender, 100)
        print("====点击")
    }
    
    @objc func actionForlongPress(sender: UILongPressGestureRecognizer){
        guard let btn = sender.view as? UIButton else{return}
        switch sender.state {
        case .began:
            btn.isSelected = true
            if !currentLongPressBtn.contains(btn) {
                currentLongPressBtn.append(btn)
            }
            startRepeatingAction()
        case .changed:
            break
        case .ended:
            btn.isSelected = false
            stopRepeatingAction()
            currentLongPressBtn.removeAll{$0 == btn}
        default:
            break
        }
    }
    func startRepeatingAction() {
        // 启动定时器，每隔 1 秒执行一次
        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(repeatingAction), userInfo: nil, repeats: true)
        // 立即执行第一次
        timer?.fire()
    }
    
    func stopRepeatingAction() {
        // 停止定时器
        timer?.invalidate()
        timer = nil
        for btn in currentLongPressBtn {
            send(btn, 300,true)
        }
    }
    
    @objc func repeatingAction() {
        for btn in currentLongPressBtn {
            send(btn, 300,false)
        }
    }
    
    /// 手动调整
    /// - Parameters:
    ///   - sender: 按钮
    ///   - time: 持续时间
    ///   - end: 是否停止充气
    private func send(_ sender:UIButton, _ t:Int, _ end:Bool=false){
        //0:停止 1:充气 2:放气
        let type = end ? "00" : [201,203,205,207,209,211].contains(sender.tag) ? "01" : "02"
        let time = String(format: "%04X", t)///工作持续时间100ms
        let airMax = slider1.type.limit.max/// 气压最大值
        let airMin = 0/// 气压最小值
        MyPrint("====结果\(type) +\(time)")
        switch sender.tag{
        case 201:///左前轮  +  气
            //attrText(min((value1!.text?.intValue() ?? 0) + 1, airMax), lbl: value1)
            BLEData.appSetDataToPer(AIQC.manualSetup.cmd, "00"+type+time).write
        case 202:///左前轮   —  气
            //attrText(max((value1!.text?.intValue() ?? 0) - 1, airMin), lbl: value1)
            BLEData.appSetDataToPer(AIQC.manualSetup.cmd, "00"+type+time).write
        case 203:///左后轮  +  气
            //attrText(min((value2!.text?.intValue() ?? 0) + 1, airMax), lbl: value2)
            BLEData.appSetDataToPer(AIQC.manualSetup.cmd, "02"+type+time).write
        case 204:///左后轮  —  气
            //attrText(max((value2!.text?.intValue() ?? 0) - 1, airMin), lbl: value2)
            BLEData.appSetDataToPer(AIQC.manualSetup.cmd, "02"+type+time).write
        case 205:///右前轮  +  气
            // attrText(min((value3!.text?.intValue() ?? 0) + 1, airMax), lbl: value3)
            BLEData.appSetDataToPer(AIQC.manualSetup.cmd, "01"+type+time).write
        case 206:///右前轮  —  气
            //attrText(max((value3!.text?.intValue() ?? 0) - 1, airMin), lbl: value3)
            BLEData.appSetDataToPer(AIQC.manualSetup.cmd, "01"+type+time).write
        case 207:///右后轮  +  气
            // attrText(min((value4!.text?.intValue() ?? 0) + 1, airMax), lbl: value4)
            BLEData.appSetDataToPer(AIQC.manualSetup.cmd, "03"+type+time).write
        case 208:///右后轮  —气
            //attrText(max((value4!.text?.intValue() ?? 0) - 1, airMin), lbl: value4)
            BLEData.appSetDataToPer(AIQC.manualSetup.cmd, "03"+type+time).write
        case 209:///左 ｜ 右前轮  +  气
            // let left = min(slider3.type.limit.max, slider3.type.current.left+1)
            // let right = min(slider3.type.limit.max, slider3.type.current.right+1)
            //slider3.type.current = (left:left,right:right)
            BLEData.appSetDataToPer(AIQC.manualSetup.cmd, "04"+type+time).write
        case 210:///左 ｜ 右前轮  —  气
            //let left = max(slider3.type.limit.min, slider3.type.current.left-1)
            //let right = max(slider3.type.limit.min, slider3.type.current.right-1)
            //slider3.type.current = (left:left,right:right)
            BLEData.appSetDataToPer(AIQC.manualSetup.cmd, "04"+type+time).write
        case 211:///左 ｜ 右后轮  +  气
            //let left = min(slider4.type.limit.max, slider4.type.current.left+1)
            //let right = min(slider4.type.limit.max, slider4.type.current.right+1)
            //slider4.type.current = (left:left,right:right)
            BLEData.appSetDataToPer(AIQC.manualSetup.cmd, "05"+type+time).write
        case 212:///左 ｜ 右后轮  —  气
            //let left = max(slider4.type.limit.min, slider4.type.current.left-1)
            //let right = max(slider4.type.limit.min, slider4.type.current.right-1)
            //slider4.type.current = (left:left,right:right)
            BLEData.appSetDataToPer(AIQC.manualSetup.cmd, "05"+type+time).write
        default:
            break
        }
    }
    private func attrText(_ num:Int, lbl:UILabel){
        let font = UIFont(name: "Lato-Regular", size: 40)!
        lbl.attributedText = "\(num)".setGradientText(colors: ["#FFFFFF".color(),"#201F1C".color(0.3)], bounds: lbl.bounds, font: font)
    }
    
    private func getCgcolor(_ progresss:CGFloat)->CGColor{
        if progresss <= 0.33 {return "#2BA6F7".color().cgColor}
        else if progresss > 0.33 && progresss <= 0.66 {return "#FD654D".color().cgColor}
        else  {return "#E01313".color().cgColor}
    }
}
